<template>
  <el-dialog v-model="dialog.visible" title="上传文件" :before-close="closeDialog">

    <el-form label-width="110">
      <el-form-item label="文件">
        <el-upload ref="upload"
                   :action="action"
                   v-model="ossModelFiles"
                   :limit="1"
                   :onExceed="onExceed"
                   :before-upload="beforeUpload"
                   :http-request="updateFile"
                   :on-success="uploadSuccess"
                   :show-file-list="true"
                   :auto-upload="false"
        >
          <template #trigger>
            <el-button text type="primary">选择文件</el-button>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="权限">
        <el-select v-model="ossModel.accessType">
          <el-option label="公共" value="public"></el-option>
          <el-option label="私有" value="private"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="存储类型">
        <el-select v-model="ossModel.storageType">
          <el-option v-for="(item) in storageTypeDict"
                     :label="item.dictName"
                     :value="item.dictVal"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否has命名">
        <el-select v-model="ossModel.hexName">
          <el-option label="是" :value="true"></el-option>
          <el-option label="否" :value="false"></el-option>
        </el-select>
      </el-form-item>
    </el-form>


    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">上传</el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script>
import {genFileId} from "element-plus";
import {getAsVal} from "components/avue/utils/util";
import {DIC_HTTP_PROPS} from "components/avue/global/variable";
import {getUploadConfig} from "@/config/env";
import baseCommonApi from "@/api/baseCommonApi";

const tempConfig = getUploadConfig();
export default {
  name: "uploadOssDialog",
  computed: {
    action() {
      return tempConfig.action
    },
    updatePropsHttp() {
      return Object.assign({}, DIC_HTTP_PROPS, tempConfig.propsHttp)
    },
  },
  props: {
    fileSize: {
      type: Number,
      default: null
    },
  },
  data() {
    return {
      dialog: {
        visible: false,
      },
      ossModelFiles: [],
      ossModel: {},
      storageTypeDict: []
    }
  },
  created() {
    baseCommonApi.loadDicDataByDictCode("start_oss_store_type").then(res => {
      this.storageTypeDict = res.data.data
    })

  },
  methods: {
    show() {
      this.ossModel = {}
      this.dialog.visible = true
    },
    onExceed(files) {
      this.$refs.upload.clearFiles();
      const file = files[0]
      file.uid = genFileId()
      this.$refs.upload.handleStart(file)
    },
    beforeUpload(rawFile) {

      if (this.fileSize === null || this.fileSize === undefined || this.fileSize < 0) {
        return true;
      }
      let fileSizeKB = rawFile.size / 1024
      this.$message.error("文件太大了，请上传小于" + this.formatFileSize(this.fileSize * 1024) + "的文件")
      return fileSizeKB <= this.fileSize;
    },
    updateFile(val) {
      let param = new FormData();


      param.append(this.updatePropsHttp.fileName, val.file);
      let keys = Object.keys(this.ossModel || {});
      for (let key of keys) {
        param.append(key, this.ossModel[key])
      }

      return this.$axios.post(val.action, param)
    },
    uploadSuccess(response, uploadFile, uploadFiles) {
      let res = getAsVal(response.data, this.updatePropsHttp.res);
      let url = getAsVal(res, this.updatePropsHttp.url)
      this.$emit("submit", [url])
      this.$refs.upload.clearFiles()
      this.closeDialog()
    },
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
    },
    closeDialog() {
      this.ossModelFiles = []
      this.ossModel = {}
      this.$refs.upload.clearFiles()
      this.dialog.visible = false;

    },
    submit() {
      let keys = Object.keys(this.ossModel);
      for (let item of keys) {
        console.log("da", item)
      }
      this.$refs.upload.submit()
    }

  },
}
</script>
<style scoped>

</style>